package com.liaoyin.travel.service.scenicInfo;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.view.scenic.EpidemicData;
import com.liaoyin.travel.view.scenic.EpidemicResultData;
import com.liaoyin.travel.view.scenic.StaffHealthCheckInfo;
import com.liaoyin.travel.view.scenic.TouristHealthCheckInfo;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.scenicInfo.EpidemicManageMapper;
import com.liaoyin.travel.dao.scenicInfo.ScenicInfoMapper;
import com.liaoyin.travel.entity.scenicInfo.EpidemicManage;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.util.*;
import com.liaoyin.travel.vo.scenic.PageInfoParameter;
import com.liaoyin.travel.vo.scenic.StaffHealthCheckInfoVo;
import com.liaoyin.travel.vo.scenic.TouristHealthCheckInfoVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 疫情管理Service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-02-22 22:58
 */
@Service
public class EpidemicManageService extends BaseService<EpidemicManageMapper, EpidemicManage> {

    @Resource
    ScenicInfoMapper scenicInfoMapper;

    /**
     * 服务器文件地址
     */
    @Value("${gate.file.server}")
    private String serverAddress;

    /**
     * 查询景区游客信息 url
     */
    @Value("${epidemic.url.getTouristHealthCheckInfo}")
    private String getTouristHealthCheckInfo;

    /**
     * 查询景区游客信息(带分页) url
     */
    @Value("${epidemic.url.getPageTouristHealthCheckInfo}")
    private String getPageTouristHealthCheckInfo;

    /**
     * 查询景区员工信息 url
     */
    @Value("${epidemic.url.getStaffHealthCheckInfo}")
    private String getStaffHealthCheckInfo;

    /**
     * 查询景区员工信息(带分页) url
     */
    @Value("${epidemic.url.getPageStaffHealthCheckInfo}")
    private String getPageStaffHealthCheckInfo;

    /**
     * @方法名：updateEpidemicManage
     * @描述： 启用或禁用疫情管理
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/22 23:19
     */
    @Transactional(rollbackFor=BusinessException.class)
    public int updateEpidemicManage(String epidemicId,String isUsing) {
        if(!VariableConstants.STRING_CONSTANT_0.equals(isUsing) && !VariableConstants.STRING_CONSTANT_1.equals(isUsing)){
            throw new BusinessException("parameter.is.invalid");
        }
        return this.mapper.updateEpidemicManage(epidemicId,isUsing);
    }

    /**
     * @方法名：insertOrUpdateEpidemicManage
     * @描述： 新增或更新-疫情管理信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/23 12:04
     */
    @Transactional(rollbackFor=BusinessException.class)
    public int insertOrUpdateEpidemicManage(EpidemicManage epidemicManage) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        int result = 0;
        String id = epidemicManage.getId();
        if(StringUtil.isBlank(id)){
            /** 新增 */
            epidemicManage.setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now()).setScenicId(scenicId);
            result = this.mapper.insert(epidemicManage);
        }else{
            /** 更新 */
            epidemicManage.setUpdateTime(LocalDateTime.now());
            result = this.mapper.updateEpidemicManageSelective(epidemicManage);
        }
        return result;
    }

    /**
     * @方法名：selectEpidemicManageById
     * @描述： 根据id查询疫情管理详情
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/23 12:24
     */
    public EpidemicManage selectEpidemicManageById(String id) {
        EpidemicManage epidemicManage = this.mapper.selectEpidemicManageById(id);
        return epidemicManage;
    }

    /**
     * @方法名：deleteEpidemicManageByIds
     * @描述： 根据ids批量删除疫情管理
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/23 12:30
     */
    public int deleteEpidemicManageByIds(String ids) {
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("not.login");
        }

        if(ids == null) {
            throw new BusinessException("id.is.null");
        }

        String[] idArray = ids.split(",");
        return this.mapper.deleteEpidemicManageByIds(idArray);
    }

    /**
     * @方法名：selectEpidemicInfo
     * @描述： 查询疫情管理信息(带分页)
     * @作者： kjz
     * @日期： Created in 2020/2/23 18:49
     */
    public PageInfo<EpidemicManage> selectEpidemicInfo(Integer num, Integer size) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        PageHelper.startPage(num,size);
        List<EpidemicManage> list = this.mapper.selectEpidemicInfo(scenicId);
        list.forEach(epidemicManage -> {
            epidemicManage.setImgUrl(serverAddress+epidemicManage.getImgUrl());
        });
        PageInfo<EpidemicManage> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * @方法名：getPageTouristHealthCheckInfo
     * @描述： 按条件查询景区游客信息(带分页)
     * @作者： kjz
     * @日期： Created in 2020/3/2 18:03
     */
    public PageInfo<TouristHealthCheckInfo> getPageTouristHealthCheckInfo(TouristHealthCheckInfoVo touristHealthCheckInfoVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        Integer pageNum = touristHealthCheckInfoVo.getNum();
        Integer pageSize = touristHealthCheckInfoVo.getSize();
        if(pageNum==null){
            pageNum = 1;
        }
        if(pageSize==null){
            pageSize = 10;
        }

        Map<String, String> params = new HashMap<>();
        params.put("scenicId",scenicId);
        params.put("pageNum",pageNum.toString());
        params.put("pageSize",pageSize.toString());

        String beginTime = touristHealthCheckInfoVo.getBeginTime();
        String endTime = touristHealthCheckInfoVo.getEndTime();
        //验证搜索的开始时间和结束时间格式是否正确，若错误则抛出异常
        if(beginTime!=null){
            ServiceUtil.verifyDateByTourist(beginTime,1);
            params.put("beginTime",beginTime);
        }
        if(endTime!=null){
            ServiceUtil.verifyDateByTourist(endTime,2);
            params.put("endTime",endTime);
        }

        String healthState = touristHealthCheckInfoVo.getHealthState();

        //验证健康状态传值是否正确，错误则抛出异常
        if(healthState!=null){
            ServiceUtil.verifyHealthState(healthState);
            params.put("healthState",healthState);
        }

        String url = getPageTouristHealthCheckInfo;
        String result = RestTemplateUtil.getRequest(url,params);
        System.out.println(result);
        EpidemicResultData resultData = JSONObject.parseObject(result,EpidemicResultData.class);
        String status = resultData.getStatus();
        //查询失败，抛出异常
        if(status.equals("400")){
            throw new BusinessException("the.query.fails",resultData.getMessage());
        }
        EpidemicData data = JSONObject.parseObject(resultData.getData(),EpidemicData.class);
        System.err.println(data);
        PageInfo<TouristHealthCheckInfo> pageInfo = new PageInfo<>();

        PageInfoParameter pageInfoParameter = ServiceUtil.createPageInfo(data.getTotal(),pageNum,pageSize);

        pageInfo .setPageNum(pageInfoParameter.getPageNum());
        pageInfo .setPageSize(pageInfoParameter.getPageSize());
        pageInfo.setSize(pageInfoParameter.getSize());
        pageInfo.setTotal(pageInfoParameter.getTotal());
        pageInfo.setPages(pageInfoParameter.getPages());
        pageInfo.setPrePage(pageInfoParameter.getPrePage());
        pageInfo.setNextPage(pageInfoParameter.getNextPage());
        pageInfo.setHasPreviousPage(pageInfoParameter.isHasPreviousPage());
        pageInfo.setHasNextPage(pageInfoParameter.isHasNextPage());
        pageInfo.setFirstPage(pageInfoParameter.getNavigateFirstPage());
        pageInfo .setLastPage(pageInfoParameter.getNavigateLastPage());
        pageInfo.setNavigatepageNums(pageInfoParameter.getNavigatepageNums());
        pageInfo.setNavigateFirstPage(pageInfoParameter.getNavigateFirstPage());
        pageInfo.setNavigateLastPage(pageInfoParameter.getNavigateLastPage());
        pageInfo.setList(data.getRows());

        return pageInfo;

    }

    /**
     * @方法名：getPageStaffHealthCheckInfo
     * @描述： 按条件查询景区员工信息(带分页)
     * @作者： kjz
     * @日期： Created in 2020/3/3 10:27
     */
    public PageInfo<StaffHealthCheckInfo> getPageStaffHealthCheckInfo(StaffHealthCheckInfoVo staffHealthCheckInfoVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        Integer pageNum = staffHealthCheckInfoVo.getNum();
        Integer pageSize = staffHealthCheckInfoVo.getSize();
        if(pageNum==null){
            pageNum = 1;
        }
        if(pageSize==null){
            pageSize = 10;
        }

        Map<String, String> params = new HashMap<>();
//        params.put("scenicId","1233651033104846848");
        System.err.println("scenicId="+scenicId);
        params.put("scenicId",scenicId);
        params.put("pageNum",pageNum.toString());
        params.put("pageSize",pageSize.toString());

        String healthState = staffHealthCheckInfoVo.getHealthState();

        //验证健康状态传值是否正确，错误则抛出异常
        if(healthState!=null){
            ServiceUtil.verifyHealthState(healthState);
            params.put("healthState",healthState);
        }

        String url = getPageStaffHealthCheckInfo;
        String result = RestTemplateUtil.getRequest(url,params);
        System.out.println(result);
        EpidemicResultData resultData = JSONObject.parseObject(result,EpidemicResultData.class);
        String status = resultData.getStatus();
        //查询失败，抛出异常
        if(status.equals("400")){
            throw new BusinessException("the.query.fails",resultData.getMessage());
        }

        JSONObject jsonObject = JSONObject.parseObject(resultData.getData());
        Integer total = jsonObject.getInteger("total");
        System.err.println("total="+total);

        List<StaffHealthCheckInfo> list = JSONObject.parseArray(jsonObject.getString("rows"),StaffHealthCheckInfo.class);
        PageInfo<StaffHealthCheckInfo> pageInfo = new PageInfo<>();

        PageInfoParameter pageInfoParameter = ServiceUtil.createPageInfo(total,pageNum,pageSize);

        pageInfo .setPageNum(pageInfoParameter.getPageNum());
        pageInfo .setPageSize(pageInfoParameter.getPageSize());
        pageInfo.setSize(pageInfoParameter.getSize());
        pageInfo.setTotal(pageInfoParameter.getTotal());
        pageInfo.setPages(pageInfoParameter.getPages());
        pageInfo.setPrePage(pageInfoParameter.getPrePage());
        pageInfo.setNextPage(pageInfoParameter.getNextPage());
        pageInfo.setHasPreviousPage(pageInfoParameter.isHasPreviousPage());
        pageInfo.setHasNextPage(pageInfoParameter.isHasNextPage());
        pageInfo.setFirstPage(pageInfoParameter.getNavigateFirstPage());
        pageInfo .setLastPage(pageInfoParameter.getNavigateLastPage());
        pageInfo.setNavigatepageNums(pageInfoParameter.getNavigatepageNums());
        pageInfo.setNavigateFirstPage(pageInfoParameter.getNavigateFirstPage());
        pageInfo.setNavigateLastPage(pageInfoParameter.getNavigateLastPage());
        pageInfo.setList(list);

        return pageInfo;
    }
    
    /**
     * @方法名：exportTouristHealthCheckInfoExcelByDate
     * @描述： 按条件导出景区游客excel文件
     * @作者： kjz
     * @日期： Created in 2020/3/3 12:23
     */
    public String exportTouristHealthCheckInfoExcelByDate(String beginTime, String endTime, String healthState) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        Map<String, String> params = new HashMap<>();
        params.put("scenicId",scenicId);

        //验证搜索的开始时间和结束时间格式是否正确，若错误则抛出异常
        if(beginTime!=null){
            ServiceUtil.verifyDateByTourist(beginTime,1);
            params.put("beginTime",beginTime);
        }
        if(endTime!=null){
            ServiceUtil.verifyDateByTourist(endTime,2);
            params.put("endTime",endTime);
        }

        //验证健康状态传值是否正确，错误则抛出异常
        if(healthState!=null){
            ServiceUtil.verifyHealthState(healthState);
            params.put("healthState",healthState);
        }
        //get请求到所有景区游客数据
        String result = RestTemplateUtil.getRequest(getTouristHealthCheckInfo,params);

        EpidemicResultData resultData = JSONObject.parseObject(result,EpidemicResultData.class);
        String status = resultData.getStatus();
        //查询失败，抛出异常
        if(status.equals("400")){
            throw new BusinessException("the.query.fails",resultData.getMessage());
        }

        List<TouristHealthCheckInfo> list = JSONObject.parseArray(resultData.getData(),TouristHealthCheckInfo.class);
        System.out.println(list);
        Map<String,String> key= new LinkedHashMap<>();
        key.put("touristName","游客姓名");
        key.put("phoneNum","联系电话");
        key.put("idCard","身份号码");
        key.put("location","游客来源地");
        key.put("symptom","有无可疑症状");
        key.put("contactHistory","接触人员是否有确诊或可疑症状病例");
        key.put("healthState","健康状态");
        key.put("temp","体温℃");
        key.put("createTime","审核时间");
        String scenicName = this.scenicInfoMapper.selectScenicNameByScenicId(scenicId);

       return ExcelUtil.excelDataList(Collections.singletonList(list),key,"【"+scenicName+"】游客信息",1000);
    }

    /**
     * @方法名：exportStaffHealthCheckInfoExcel
     * @描述： 按条件导出景区员工excel文件
     * @作者： kjz
     * @日期： Created in 2020/3/4 12:02
     */
    public String exportStaffHealthCheckInfoExcel(String healthState) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        Map<String, String> params = new HashMap<>();
        params.put("scenicId",scenicId);

        //验证健康状态传值是否正确，错误则抛出异常
        if(healthState!=null){
            ServiceUtil.verifyHealthState(healthState);
            params.put("healthState",healthState);
        }
        //get请求到所有景区游客数据
        String result = RestTemplateUtil.getRequest(getStaffHealthCheckInfo,params);

        EpidemicResultData resultData = JSONObject.parseObject(result,EpidemicResultData.class);
        String status = resultData.getStatus();
        //查询失败，抛出异常
        if(status.equals("400")){
            throw new BusinessException("the.query.fails",resultData.getMessage());
        }

        List<StaffHealthCheckInfo> list = JSONObject.parseArray(resultData.getData(),StaffHealthCheckInfo.class);
        System.out.println(list);
        Map<String,String> key= new LinkedHashMap<>();
        key.put("staffName","姓名");
        key.put("phoneNum","联系电话");
        key.put("idCard","身份号码");
        key.put("location","游客来源地");
        key.put("symptom","有无可疑症状");
        key.put("contactHistory","接触人员是否有确诊或可疑症状病例");
        key.put("healthState","健康状态");
        key.put("temp","体温℃");

        String scenicName = this.scenicInfoMapper.selectScenicNameByScenicId(scenicId);

        return ExcelUtil.excelDataList(Collections.singletonList(list),key,"【"+scenicName+"】员工信息",1000);
    }
}
